﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Reflection;
using System.IO;

namespace GeoVision.Addin.Core.Server
{
    class TemporaryWebServer : IDisposable
    {
        private System.Net.HttpListener listener = new System.Net.HttpListener();
        private Thread thread = null;
        public int Port { get; set; }

        public void Start()
        {
            ThreadStart ts = new ThreadStart(internalStart);
            thread = new Thread(ts);
            thread.Start();

        }

        public void Stop()
        {
            if (thread != null && thread.ThreadState == ThreadState.Running)
            {
                thread.Abort();
            }
            if (listener.IsListening)
                listener.Stop();
        }

        private void internalStart()
        {
            listener.Prefixes.Add(string.Format("http://localhost:{0}/", Port));
            listener.Start();
            while (Thread.CurrentThread.ThreadState == ThreadState.Running)
            {
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request = context.Request;
                HttpListenerResponse response = context.Response;
                if (request.QueryString["type"] == "html")
                    FillHtmlContent(response);
                else if (request.QueryString["type"] == "xap")
                    FillSilverlightApp(response);
                response.OutputStream.Close();
            }
            listener.Stop();
        }

        private void FillSilverlightApp(HttpListenerResponse response)
        {
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("GeoVision.Addin.Resources.BingMap.xap");
            stream.Seek(0, SeekOrigin.Begin);
            stream.CopyTo(response.OutputStream);
            response.ContentType = "text/html";
        }

        private void FillHtmlContent(HttpListenerResponse response)
        {
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("GeoVision.Addin.Resources.BingMapContent.htm");
            stream.Seek(0, SeekOrigin.Begin);
            stream.CopyTo(response.OutputStream);
            response.ContentType = "application/x-silverlight-app";
        }

        public TemporaryWebServer()
        {
            this.Port = new Random().Next(800, 1000);
        }
        #region IDisposable Members
        public void Dispose()
        {
            Stop();
        }

        #endregion
    }
}
